package com.alog.javaee.day41;

import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Auther: Ye Zhengdong
 * @Date: 2019/2/20 18:52
 * @Description:
 */
@WebServlet("/day41/loginServlet3")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String verifycode = req.getParameter("verifycode");
        String sessionCheckCode = (String) req.getSession().getAttribute("sessionCheckCode");
        req.getSession().removeAttribute("sessionCheckCode");
        if(sessionCheckCode != null && !sessionCheckCode.equalsIgnoreCase(verifycode)){
            req.setAttribute("login_msg", "验证码错误");
            req.getRequestDispatcher("/day41/login.jsp").forward(req, resp);
            return;
        }

        Map<String, String[]> parameterMap = req.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService service = new UserServiceImpl();
        User loginUser = service.login(user);
        if(loginUser != null){
            req.getSession().setAttribute("user", loginUser);
            resp.sendRedirect(req.getContextPath() + "/day41/index.jsp");
        } else {
            req.setAttribute("login_msg", "用户名或密码错误");
            req.getRequestDispatcher("/day41/login.jsp").forward(req, resp);
            return;
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
